package com.ken.apollo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步任务线程池配置类
 * 用于邮件发送等异步任务的线程池管理
 *
 * @author Ken
 * @since 2025-08-25
 */
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {

    /**
     * 邮件发送专用线程池
     * 根据CPU核心数动态配置线程池参数
     */
    @Bean("mailTaskExecutor")
    public ThreadPoolTaskExecutor mailTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 获取CPU核心数
        int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;
        int maxPoolSize = corePoolSize * 4;
        
        // 核心线程数：CPU核心数
        executor.setCorePoolSize(corePoolSize);
        
        // 最大线程数：CPU核心数 * 2
        executor.setMaxPoolSize(maxPoolSize);
        
        // 队列容量：核心线程数 * 10，避免过多任务堆积
        executor.setQueueCapacity(1000);
        
        // 线程名前缀
        executor.setThreadNamePrefix("mail-async-");
        
        // 线程空闲时间：60秒
        executor.setKeepAliveSeconds(60);
        
        // 拒绝策略：调用者运行策略（在调用线程中执行被拒绝的任务）
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 等待时间：30秒
        executor.setAwaitTerminationSeconds(30);
        
        // 初始化线程池
        executor.initialize();
        
        log.info("【邮件线程池初始化完成】CPU核心数：{}, 核心线程数：{}, 最大线程数：{}, 队列容量：{}", 
            Runtime.getRuntime().availableProcessors(), corePoolSize, maxPoolSize, 1000);
        
        return executor;
    }

    /**
     * 通用异步任务线程池
     * 用于其他异步任务
     */
    @Bean("commonTaskExecutor")
    public ThreadPoolTaskExecutor commonTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = corePoolSize * 4;
        
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(corePoolSize * 20);
        executor.setThreadNamePrefix("common-async-");
        executor.setKeepAliveSeconds(120);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        
        log.info("【通用线程池初始化完成】CPU核心数：{}, 核心线程数：{}, 最大线程数：{}, 队列容量：{}", 
            Runtime.getRuntime().availableProcessors(), corePoolSize, maxPoolSize, corePoolSize * 20);
        
        return executor;
    }

    /**
     * 默认异步执行器
     */
    @Override
    public Executor getAsyncExecutor() {
        return commonTaskExecutor();
    }

    /**
     * 异步任务异常处理器
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            log.error("【异步任务执行异常】方法：{}.{}, 参数：{}, 异常信息：{}", 
                method.getDeclaringClass().getSimpleName(), 
                method.getName(), 
                objects, 
                throwable.getMessage(), 
                throwable);
        };
    }
}